package com.jx.mlxg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jx.mlxg.entity.*;
import com.jx.mlxg.mapper.ApprovalNodeMapper;
import com.jx.mlxg.mapper.ApprovalRecordMapper;
import com.jx.mlxg.mapper.UsersMapper;
import com.jx.mlxg.service.ApprovalFlowService;
import com.jx.mlxg.mapper.ApprovalFlowMapper;
import com.jx.mlxg.service.OrdersService;
import com.jx.mlxg.service.UsersService;
import com.jx.mlxg.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @author Administrator
* @description 针对表【approval_flow】的数据库操作Service实现
* @createDate 2025-03-14 16:29:13
*/
@Service
public class ApprovalFlowServiceImpl extends ServiceImpl<ApprovalFlowMapper, ApprovalFlow>
    implements ApprovalFlowService{

    @Autowired
    private ApprovalNodeMapper approvalNodeMapper;
    @Autowired
    private ApprovalRecordMapper approvalRecordMapper;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public void startApprovalFlow(String orderId, Long userId) {
        // 检查订单是否存在
        Orders order = ordersService.getBaseMapper().selectById(orderId);
        if (order == null) {
            throw new IllegalArgumentException("订单不存在");
        }

        // 检查用户是否存在
        Users user = usersMapper.getByUserId(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 获取审批流定义
        ApprovalFlow approvalFlow = getOne(new QueryWrapper<ApprovalFlow>()
                .eq("flow_name", "工厂发货审批"));
        if (approvalFlow == null) {
            throw new IllegalArgumentException("审批流定义不存在");
        }

        // 获取第一个审批节点（工厂管理员审批）
        ApprovalNode firstNode = approvalNodeMapper.selectOne(new QueryWrapper<ApprovalNode>()
                .eq("flow_id", approvalFlow.getFlowId())
                .eq("node_role", 2) // 工厂管理员角色
                .orderByAsc("node_order")
                .last("LIMIT 1"));
        if (firstNode == null) {
            throw new IllegalArgumentException("审批节点定义不存在");
        }

        // 创建审批记录
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setOrderId(orderId);
        approvalRecord.setNodeId(firstNode.getNodeId());
        approvalRecord.setUsersId(userId); // 待审批
        approvalRecord.setApproveStatus("审批中");
        approvalRecord.setApproveTime(LocalDateTime.now());
        approvalRecordMapper.insert(approvalRecord);

        // 更新订单状态为待审批
        order.setStatus("审批中");
        ordersService.updateById(order);

        // 提醒工厂管理员
        remindApprover(orderId, firstNode.getNodeId());
    }

    @Override
    public ResponseResult approve(String orderId, String approveStatus, String approveOpinion,boolean isAuto) {
        HashMap<Object, Object> map = new HashMap<>();
        boolean bool =  false;
        map.put("isSuccess", bool);
        Long usersId;

        if(isAuto){
            usersId = 1002L;
        }else{
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            // 假设 principal 是一个字符串，表示用户的 openId 或 userId
            String openIdStr = (String) principal;
            // 根据 userId 获取用户信息和订单统计
            Users userInfoAndOrderStatistics = usersService.findByOpenId(openIdStr);
             usersId = userInfoAndOrderStatistics.getUserId();
        }

        // 获取当前审批记录
        ApprovalRecord currentRecord = approvalRecordMapper.selectOne(new QueryWrapper<ApprovalRecord>()
                .eq("order_id", orderId)
                .eq("approve_status", "审批中"));
        if (currentRecord == null) {
            return ResponseResult.success(map);
//            throw new IllegalArgumentException("当前审批记录不存在或已处理");
        }

        // 获取当前审批节点
        ApprovalNode currentNode = approvalNodeMapper.selectById(currentRecord.getNodeId());
        if (currentNode == null) {
//            throw new IllegalArgumentException("审批节点不存在");
            return ResponseResult.success(map);
        }

        // 获取审批人信息
        Users approver = usersMapper.getByUserId(usersId);
        if (approver == null) {
            return ResponseResult.success(map);
//            throw new IllegalArgumentException("审批人不存在");
        }

        // 校验审批人是否具有当前节点所需的角色
        if (approver.getRole()!= 0 ) {
            if(approver.getRole() != 1 && !approver.getRole().equals(currentNode.getNodeRole())){
                return ResponseResult.success(map);
//                throw new IllegalArgumentException("当前用户无权审批该节点");
            }

        }

        // 更新审批记录
        currentRecord.setUsersId(usersId);
        currentRecord.setApproveStatus(approveStatus);
        currentRecord.setApproveOpinion(approveOpinion);
        currentRecord.setApproveTime(LocalDateTime.now());
        approvalRecordMapper.updateById(currentRecord);

        // 如果审批通过，判断是否还有下一个节点
        if ("审批通过".equals(approveStatus)) {
            // 获取下一个审批节点
            ApprovalNode nextNode = approvalNodeMapper.selectOne(new QueryWrapper<ApprovalNode>()
                    .eq("flow_id", currentNode.getFlowId())
                    .gt("node_order", currentNode.getNodeOrder())
                    .orderByAsc("node_order")
                    .last("LIMIT 1"));

            if (nextNode != null) {
                // 创建下一个节点的审批记录
                ApprovalRecord nextRecord = new ApprovalRecord();
                nextRecord.setOrderId(orderId);
                nextRecord.setNodeId(nextNode.getNodeId());
                nextRecord.setUsersId(usersId);
                nextRecord.setApproveStatus("审批中");
                nextRecord.setApproveTime(LocalDateTime.now());
                approvalRecordMapper.insert(nextRecord);

                // 提醒下一个审批人
                remindApprover(orderId, nextNode.getNodeId());
            } else {
                // 没有更多节点，审批流程结束
                QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>().eq("order_id", orderId);
                Orders order = ordersService.getOne(queryWrapper);
                order.setStatus("审批通过");
                ordersService.updateById(order);
            }
        } else if ("审批拒绝".equals(approveStatus)) {
            // 审批拒绝，流程结束
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>().eq("order_id", orderId);
            Orders order = ordersService.getOne(queryWrapper);
            order.setStatus("审批拒绝");
            ordersService.updateById(order);
        }

        return ResponseResult.success(map);
    }

    @Override
    public ApprovalRecord getApprovalRecords(String orderId) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 假设 principal 是一个字符串，表示用户的 openId 或 userId
        if (principal instanceof String) {
            String openIdStr = (String) principal;
            // 根据 userId 获取用户信息和订单统计
            Users userInfoAndOrderStatistics = usersService.findByOpenId(openIdStr);
//            Orders orderById = ordersService.getOrderById(orderId, userInfoAndOrderStatistics.getOpenId());
            ApprovalRecord approvalRecord = ordersService.getApprovalRecordByOrderId(orderId, userInfoAndOrderStatistics);
            return approvalRecord;
        }
        return null;
    }

    @Override
    public ApprovalNode getCurrentNode(String orderId) {
        ApprovalRecord currentRecord = approvalRecordMapper.selectOne(new QueryWrapper<ApprovalRecord>()
                .eq("order_id", orderId)
                .eq("approve_status", "审批中"));
        if (currentRecord != null) {
            return approvalNodeMapper.selectById(currentRecord.getNodeId());
        }
        return null;
    }

    @Override
    public void remindApprover(String orderId, Integer nodeId) {
        // 实现提醒逻辑，例如发送消息通知
        ApprovalNode node = approvalNodeMapper.selectById(nodeId);
        if (node != null) {
            // 根据节点角色获取审批人列表
            List<Users> approvers = usersService.list(new QueryWrapper<Users>()
                    .eq("role", node.getNodeRole()));

            // 发送提醒通知
            approvers.forEach(approver -> {
                // 调用消息通知服务发送提醒
                // sendMessage(approver.getUserId(), "您有一条新的审批任务");
            });
        }
    }
}




